﻿using Hx.ADSyncPlatform.Auth.Model;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;

namespace Hx.ADSyncPlatform.Auth
{
    public class JwtService
    {
        public enum TokenType
        {
            AccessToken,
            RefreshToken

        }
        public static TokenInfoViewModel.TokenModel BuildJwtToken(Claim[] claims, PermissionRequirement permissionRequirement, TokenType tokenType = TokenType.AccessToken)
        {

            var now = DateTime.Now;
            // 实例化JwtSecurityToken
            var jwt = new JwtSecurityToken(
                issuer: permissionRequirement.Issuer,
                audience: permissionRequirement.Audience,
                claims: claims,
                notBefore: now,
                expires: now.Add(tokenType == TokenType.AccessToken ? permissionRequirement.AccessTokenExpire : permissionRequirement.RefreshTokenExpire),
                signingCredentials: permissionRequirement.SigningCredentials
            );
            // 生成 Token
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

            //打包返回前台
            var responseJson = new TokenInfoViewModel.TokenModel
            {

                token = encodedJwt,
                expires_in = permissionRequirement.Expiration.TotalSeconds,
                token_type = "Bearer"
            };
            return responseJson;
        }

        public static bool TokenValid(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            try
            {
                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }
        /// <summary>
        /// 解析
        /// </summary>
        /// <param name="jwtStr"></param>
        /// <returns></returns>
        public static Guid GetUserIdByToken(string jwtStr)
        {
            var jwtHandler = new JwtSecurityTokenHandler();
            try
            {
                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
                object role;
                jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);

                object userId;
                jwtToken.Payload.TryGetValue(JwtRegisteredClaimNames.Jti, out userId);

                return Guid.Parse(userId.ToString());
            }
            catch (Exception)
            {
                return Guid.Empty;
            }

        }

        public static string GetClaimValueByType(string token, string claimType)
        {
            try
            {
                var jwtHandler = new JwtSecurityTokenHandler();

                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(token);

                return (from item in jwtToken.Claims
                        where item.Type == claimType
                        select item.Value).ToList().FirstOrDefault();
            }
            catch (Exception ex)
            {

                return "";
            }


        }
    }
}
